<?php

namespace app\common\model\xiluedu;

use think\Model;
use function fast\array_get;


class Topic extends Model
{

    

    

    // 表名
    protected $name = 'xiluedu_topic';

    // 追加属性
    protected $append = [
        'status_text',
        'top_status_text'
    ];

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getTopStatusList()
    {
        return ['0' => __('Top_status 0'), '1' => __('Top_status 1')];
    }

    public function getImageAttr($value,$data){
        return $value ? cdnurl($value,true) : "";
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTopStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['top_status']) ? $data['top_status'] : '');
        $list = $this->getTopStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 置顶话题
     * @param int $pagesize
     */
    public static function topLists($pagesize = 6){
        $forum_model = new TopicForum();
        $lists = self::field('weigh,createtime,updatetime',true)
            ->where('status',1)
            ->where('top_status','1')
            ->order('top_status','desc')
            ->order('updatetime','desc')
            ->limit($pagesize)
            ->select();
        foreach ($lists as $list){
            $list->forumuser_count = $forum_model->where('topic_id',$list->id)->group('user_id')->count();
        }
        return $lists;
    }


    /**
     * 话题列表
     * @param $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function lists($params){
        $forum_model = new TopicForum();
        $pagesize = array_get($params,'pagesize',10);
        $where['status'] = 1;
        if($top_status = array_get($params,'top_status')){
            $where['top_status'] = $top_status;
        }
        //搜索
        if($q = array_get($params,'q')){
            $where['name'] = ['like',"%$q%"];
        }
        return self::where($where)
            ->order('updatetime','desc')
            ->paginate($pagesize)
            ->each(function ($row) use($forum_model){
                $row->forumuser_count = $forum_model->where('topic_id',$row->id)->group('user_id')->count();
            });
    }


}
